package com.aircms.controller.admin;

import com.aircms.common.ServerResponse;
import com.aircms.controller.BaseAdminController;
import com.aircms.pojo.Users;
import com.aircms.pojo.validation.BaseQueryFieldsValidation;
import com.aircms.pojo.vo.RolePermissionVo;
import com.aircms.pojo.vo.UserRoleVo;
import com.aircms.service.IRolePermissionService;
import com.aircms.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author air
 * @create 2018-07-03 上午10:14
 */
@RestController
@RequestMapping(value = "api/admin/auth/users")
public class UsersAdminController extends BaseAdminController {
    @Autowired
    private IUsersService iUsersService;

    @Autowired
    private IRolePermissionService iRolePermissionService;

    /**
     * Display a listing of the resource.
     *
     * @return
     */
    @GetMapping(value = (""))
    public ServerResponse index(BaseQueryFieldsValidation baseQueryFields) throws Exception{
        try {
            return iUsersService.index(baseQueryFields,getPageNum(),getPageSize());
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("查询失败");
        }
    }



    /**
     * Store a newly created resource in storage.
     *
     * @return
     */
    @PostMapping(value = "")
    public ServerResponse store(Users user)  throws Exception{
        try {
            return iUsersService.store(user);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("添加失败");
        }
    }


    /**
     * Display the specified resource.
     *
     * @param id
     * @return
     */
    @GetMapping(value = "{id}")
    public ServerResponse show(@PathVariable Integer id) throws Exception{
        try {
            return iUsersService.show(id);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("查询失败");
        }
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param id
     * @return
     */
    @GetMapping(value = "{id}/edit")
    public ServerResponse edit(@PathVariable Integer id) throws  Exception{
        try {
            return ServerResponse.response();
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("查询失败");
        }
    }


    /**
     * Update the specified resource in storage.
     *
     * @return
     */
    @RequestMapping(value = "{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
    public ServerResponse update(@PathVariable Integer id, @Validated Users users, BindingResult bindingResult) throws Exception{
        try {
            if(bindingResult.hasErrors()){ // 表单验证
                return ServerResponse.response("",-800,bindingResult.getFieldError().getDefaultMessage());
            }
            return iUsersService.update(users);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("更新失败");
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "{id}")
    public ServerResponse destroy(@PathVariable Integer id) throws Exception{
        try {
            return iUsersService.destroy(id);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("删除失败");
        }
    }


    /**
     * 获取登录用户信息
     * @return
     */
    @GetMapping(value = "getLoginUserInfo")
    public ServerResponse getLoginUserInfo() throws Exception{
        try{
            return iUsersService.show(getUserId());
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("获取登录用户信息失败");
        }
    }


    /**
     * 获取用户的菜单权限
     * @return
     */
    @GetMapping(value ="getUserMenuPermission")
    public ServerResponse getUserMenuPermission() throws Exception{
        try{
            String string=getUserRoleId();
            String[] roleIds=string.split(",");

            List<RolePermissionVo> rolePermissions= (List<RolePermissionVo>) iRolePermissionService.getRoleMenuPermissionIds(roleIds).getData();

            return ServerResponse.response(rolePermissions);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("获取用户菜单权限失败");
        }
    }

    /**
     * 更新用户信息，包括用户角色信息
     * @return
     */
    @RequestMapping(value = "updateUserAndUserRole/{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
    public ServerResponse updateUserAndUserRole(@PathVariable Integer id, UserRoleVo  userRoleVo) throws Exception{
        try {
            return iUsersService.updateUserAndUserRole(userRoleVo);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("更新用户/用户角色失败");
        }
    }

    /**
     * 登录用户自己修改密码
     * @param id
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "updatePassword/{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
    public ServerResponse updatePassword(@PathVariable Integer id, String oldPassword, String newPassword) throws Exception{
        try{
            return  iUsersService.updatePassword(id,oldPassword,newPassword);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("修改密码失败");
        }
    }


    /**
     * 重置用户密码
     * @param id
     * @param newPassword
     * @return
     */
    @RequestMapping(value = "resetUserPassword/{id}", method = {RequestMethod.PUT, RequestMethod.PATCH})
    public ServerResponse resetUserPassword(@PathVariable Integer id, String newPassword) throws Exception{
        try{
            if(newPassword.length()<6){
                return ServerResponse.response("",-2,"密码至少6位");
            }
            return  iUsersService.resetUserPassword(id,newPassword);
        }catch (Exception e){
            this.errorLog(this.getClass(),e);
            throw new Exception("重置密码失败");
        }
    }


}
